/**
 * axios统一配置和拦截器
 */
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'

// API基础地址
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api'

/**
 * 创建axios实例
 */
const createApiClient = (): AxiosInstance => {
  const apiClient = axios.create({
    baseURL: API_BASE_URL,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json'
    },
    withCredentials: true  // 允许携帧Cookie
  })

  /**
   * 请求拦截器：自动添加Token
   */
  apiClient.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const token = localStorage.getItem('token')
      if (token && config.headers) {
        config.headers.Authorization = `Token ${token}`
      }
      return config
    },
    (error: AxiosError) => {
      console.error('请求错误：', error)
      return Promise.reject(error)
    }
  )

  /**
   * 响应拦截器：处理错误
   */
  apiClient.interceptors.response.use(
    (response: AxiosResponse) => {
      // 直接返回响应数据
      return response
    },
    (error: AxiosError) => {
      // Token过期或无效，跳转到登录页
      if (error.response?.status === 401) {
        console.warn('Token过期或无效，跳转到登录页')
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        // 避免循环跳转
        if (window.location.pathname !== '/login') {
          window.location.href = '/login'
        }
      } else if (error.response?.status === 403) {
        console.error('权限不足')
      } else if (error.response?.status === 404) {
        console.error('资源不存在')
      } else if (error.response && error.response.status >= 500) {
        console.error('服务器错误')
      }
      return Promise.reject(error)
    }
  )

  return apiClient
}

/**
 * 导出统一的axios实例
 */
export const apiClient = createApiClient()

/**
 * 导出API基础地址
 */
export { API_BASE_URL }

/**
 * 默认导出
 */
export default apiClient